package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.model.entity.*;
import com.atguigu.lease.model.enums.ItemType;
import com.atguigu.lease.web.admin.mapper.*;
import com.atguigu.lease.web.admin.service.*;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentDetailVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentItemVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentQueryVo;
import com.atguigu.lease.web.admin.vo.apartment.ApartmentSubmitVo;
import com.atguigu.lease.web.admin.vo.fee.FeeValueVo;
import com.atguigu.lease.web.admin.vo.graph.GraphVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liubo
 * @description 针对表【apartment_info(公寓信息表)】的数据库操作Service实现
 * @createDate 2023-07-24 15:48:00
 */
@Service
public class ApartmentInfoServiceImpl extends ServiceImpl<ApartmentInfoMapper, ApartmentInfo>
        implements ApartmentInfoService {

    @Autowired
    private ApartmentInfoMapper apartmentInfoMapper;
    @Autowired
    private ApartmentFacilityService apartmentFacilityService;
    @Autowired
    private ApartmentLabelService apartmentLabelService;
    @Autowired
    private ApartmentFeeValueService apartmentFeeValueService;
    @Autowired
    private ProvinceInfoService provinceInfoService;
    @Autowired
    private CityInfoService cityInfoService;
    @Autowired
    private DistrictInfoService districtInfoService;
    @Autowired
    private GraphInfoService graphInfoService;
    @Autowired
    private GraphInfoMapper graphInfoMapper;
    @Autowired
    private FacilityInfoMapper facilityInfoMapper;
    @Autowired
    private LabelInfoMapper labelInfoMapper;
    @Autowired
    private FeeValueMapper feeValueMapper;
    @Autowired
    private RoomInfoService roomInfoService;
    /**
     * @author gengjian
     * @date 2024/12/10 09:38:01
     * 根据动态条件（省份，城市，区县）分页查询公寓列表vo（房间总数，空房间数）
     */
    @Override
    public void pageItem(IPage<ApartmentItemVo> iPage, ApartmentQueryVo queryVo) {
        apartmentInfoMapper.selectPageApartmentInfo(iPage,queryVo);
    }

    /**
     * @author gengjian
     * @date 2024/12/10 13:57:46
     * 保存或更新公寓信息及配套标签杂费图片ids
     */
    @Override
    public void saveOrUpdateApartmentSubmitVo(ApartmentSubmitVo apartmentSubmitVo) {
        //判断是保存还是更新 根据公寓id
        boolean isUpdate = apartmentSubmitVo.getId() != null;
        //前端只传了省市区id没传名称 我们自己查完设置
        apartmentSubmitVo.setProvinceName(provinceInfoService.getById(apartmentSubmitVo.getProvinceId()).getName());
        apartmentSubmitVo.setCityName(cityInfoService.getById(apartmentSubmitVo.getCityId()).getName());
        apartmentSubmitVo.setDistrictName(districtInfoService.getById(apartmentSubmitVo.getDistrictId()).getName());
        //直接更新或公寓表信息 多态
        super.saveOrUpdate(apartmentSubmitVo);
        if (isUpdate){
            //更新多条就是根据公寓id先删除配套关系 再新增
            LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,apartmentSubmitVo.getId());
            apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
            //先根据公寓id 删除标签关系 再新增
            LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,apartmentSubmitVo.getId());
            apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);
            //先根据公寓id删除 杂费关系 再新增
            LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
            apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,apartmentSubmitVo.getId());
            apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
            //先根据公寓id删除 图片信息 再新增
            LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
            graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemId,apartmentSubmitVo.getId())
                            .eq(GraphInfo::getItemType, ItemType.APARTMENT);
            graphInfoService.remove(graphInfoLambdaQueryWrapper);
        }
        //方式一
        //保存配套关系
        List<Long> facilityInfoIds = apartmentSubmitVo.getFacilityInfoIds();
        List<ApartmentFacility> facilityList = new ArrayList<>();
        for (Long facilityInfoId : facilityInfoIds) {
            ApartmentFacility apartmentFacility = ApartmentFacility.builder()
                    .apartmentId(apartmentSubmitVo.getId())
                    .facilityId(facilityInfoId)
                    .build();
            facilityList.add(apartmentFacility);
        }
        apartmentFacilityService.saveBatch(facilityList);
        //保存标签关系
        List<Long> labelIds = apartmentSubmitVo.getLabelIds();
        List<ApartmentLabel> labelList = new ArrayList<>();
        for (Long labelId : labelIds) {
            ApartmentLabel apartmentLabel = ApartmentLabel.builder()
                    .apartmentId(apartmentSubmitVo.getId())
                    .labelId(labelId)
                    .build();
            labelList.add(apartmentLabel);
        }
        apartmentLabelService.saveBatch(labelList);
        //保存杂费关系
        List<Long> feeValueIds = apartmentSubmitVo.getFeeValueIds();
        List<ApartmentFeeValue> feeValueList = new ArrayList<>();
        for (Long feeValueId : feeValueIds) {
            ApartmentFeeValue apartmentFeeValue = ApartmentFeeValue.builder()
                    .apartmentId(apartmentSubmitVo.getId())
                    .feeValueId(feeValueId)
                    .build();
            feeValueList.add(apartmentFeeValue);
        }
        apartmentFeeValueService.saveBatch(feeValueList);
        //保存图片信息
        List<GraphVo> graphVoList = apartmentSubmitVo.getGraphVoList();
        List<GraphInfo> graphInfoList = new ArrayList<>();
        for (GraphVo graphVo : graphVoList) {
            GraphInfo graphInfo = new GraphInfo();
            graphInfo.setName(graphVo.getName());
            graphInfo.setUrl(graphVo.getUrl());
            graphInfo.setItemId(apartmentSubmitVo.getId());
            graphInfo.setItemType(ItemType.APARTMENT);
            graphInfoList.add(graphInfo);
        }
        graphInfoService.saveBatch(graphInfoList);
    }

    /**
     * @author gengjian
     * @date 2024/12/11 11:48:59
     * 根据公寓id查询公寓详情信息（用于修改的回显）
     */
    @Override
    public ApartmentDetailVo getDetaildById(Long id) {
        //根据公寓id查询公寓信息
        ApartmentInfo apartmentInfo = super.getById(id);
        //根据公寓id查询图片信息
        List<GraphVo> graphVoList = graphInfoMapper.selectGraphVoList(id,ItemType.APARTMENT);
        //根据公寓id查询配套关系，再通过配套关系查配套信息
        List<FacilityInfo> facilityInfoList = facilityInfoMapper.selectFacilityInfoList(id);
        //根据公寓id查询标签关系，再通过标签关系查标签信息
        List<LabelInfo> labelInfoList = labelInfoMapper.selectLabelInfoList(id);
        //根据公寓id查询杂费值关系表，再查杂费属性，再合并封装到vo
        List<FeeValueVo> feeValueVoList = feeValueMapper.selectFeeValueVoList(id);
        //封装到ApartmentDetailVo
        ApartmentDetailVo apartmentDetailVo = new ApartmentDetailVo();
        apartmentDetailVo.setFacilityInfoList(facilityInfoList);
        apartmentDetailVo.setGraphVoList(graphVoList);
        apartmentDetailVo.setLabelInfoList(labelInfoList);
        apartmentDetailVo.setFeeValueVoList(feeValueVoList);
        //拷贝公寓信息
        BeanUtils.copyProperties(apartmentInfo,apartmentDetailVo);
        //返回vo
        return apartmentDetailVo;
    }

    /**
     * @author gengjian
     * @date 2024/12/11 11:05:30
     * 根据id删除公寓信息
     */
    @Override
    public void customRemove(Long id) {
        //先判断公寓下有无房间，如果有则拒绝删除，没有则可以删除
        LambdaQueryWrapper<RoomInfo> roomInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        roomInfoLambdaQueryWrapper.eq(RoomInfo::getApartmentId,id);
        long count = roomInfoService.count(roomInfoLambdaQueryWrapper);
        if (count > 0){
            //有房间未删除 拒绝删除抛异常
            throw new LeaseException(ResultCodeEnum.DELETE_ERROR.getCode(),ResultCodeEnum.DELETE_ERROR.getMessage());
        }
        //可以根据公寓id删除公寓信息
        super.removeById(id);
        //根据公寓id删除配套关系
        LambdaQueryWrapper<ApartmentFacility> apartmentFacilityLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFacilityLambdaQueryWrapper.eq(ApartmentFacility::getApartmentId,id);
        apartmentFacilityService.remove(apartmentFacilityLambdaQueryWrapper);
        //根据公寓id删除标签关系
        LambdaQueryWrapper<ApartmentLabel> apartmentLabelLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentLabelLambdaQueryWrapper.eq(ApartmentLabel::getApartmentId,id);
        apartmentLabelService.remove(apartmentLabelLambdaQueryWrapper);
        //根据公寓id删除杂费值关系
        LambdaQueryWrapper<ApartmentFeeValue> apartmentFeeValueLambdaQueryWrapper = new LambdaQueryWrapper<>();
        apartmentFeeValueLambdaQueryWrapper.eq(ApartmentFeeValue::getApartmentId,id);
        apartmentFeeValueService.remove(apartmentFeeValueLambdaQueryWrapper);
        //根据公寓id删除图片信息
        LambdaQueryWrapper<GraphInfo> graphInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        graphInfoLambdaQueryWrapper.eq(GraphInfo::getItemType,ItemType.APARTMENT)
                        .eq(GraphInfo::getItemId,id);
        graphInfoService.remove(graphInfoLambdaQueryWrapper);
    }
}




